using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.UI;

namespace CodeSmackdown.Web.Controllers
{
    [HandleError]
    [OutputCache(Location = OutputCacheLocation.None)]
    public class SnippetController : Controller
    {
        //
        // GET: /Snippet/

        [Authorize]
        public ActionResult Index()
        {
            ViewData["Title"] = "Submit Two Snippets";
            return View();
        }

        [Authorize]
        public ActionResult SubmitSuccess()
        {
            ViewData.Model = TempData["SavedSnippet"] as Models.Snippet;
            return View();
        }

        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Index(string title, string snippet1, string snippet2)
        {
            ViewData["Title"] = "Submit Your Snippet!";

            // Basic parameter validation
            if (String.IsNullOrEmpty(title))
            {
                ModelState.AddModelError("title", "Snippet needs to have a title!");
            }
            if (String.IsNullOrEmpty(snippet1))
            {
                ModelState.AddModelError("snippet1", "Specify a snippet on the left, Knuth!");
            }
            if (String.IsNullOrEmpty(snippet2))
            {
                ModelState.AddModelError("snippet2", "Specify a snippet on the right, Yegge!");
            }

            if (ModelState.IsValid)
            {
                var snippet = SaveSnippet(title, snippet1, snippet2);
                if(snippet != null)
                {
                    TempData["SavedSnippet"] = snippet;
                    return RedirectToAction("SubmitSuccess");
                }
                ViewData["Message"] = "Unable to save snippet.";
            }

            return View();
        }

        private Models.Snippet SaveSnippet(string title, string snippet1, string snippet2)
        {
            Models.CodeSmackdownDataContext ctx = new CodeSmackdown.Web.Models.CodeSmackdownDataContext();
            return ctx.SaveNewSnippet(title, snippet1, snippet2, Session.User());
        }

    }
}
